import * as React from "react";
import { Input, Select, Modal, Table } from "antd";
import {
  AjaxData,
  columnsDataCLass,
} from "../../../../../../data/interface/publicInterface";
import { ergodicListAddIdToKey } from "../../../../../../utils/common";
import { getFindDevice } from "../../../ServeApi";

const { Search } = Input;

export interface SelectDeviceProps {
  energyType: string;
  style?: any;
  onSelect: (data: any) => any;
}

export interface SelectDeviceState {
  value: string;
  isModalVisible: boolean;
  loading: boolean;
  pageIndex: number;
  pageSize: number;
  total: number;
  searTxt: string;
  dataSource: any[];
}

class SelectDevice extends React.Component<
  SelectDeviceProps,
  SelectDeviceState
> {
  state = {
    loading: false,
    value: "",
    isModalVisible: false,
    pageIndex: 1,
    pageSize: 5,
    total: 0,
    searTxt: "",
    dataSource: [],
  };
  private columns: columnsDataCLass[] = [
    {
      title: "设备名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "编号",
      dataIndex: "no",
      key: "no",
    },
  ];
  private initValue: any | null = null;
  private selectedRow: any = null;
  render() {
    let { isModalVisible } = this.state;
    return (
      <>
        <Select
          value={this.state.value}
          style={this.props.style}
          open={false}
          onClick={() => {
            this.openTheModal();
          }}
        ></Select>
        <Modal
          title="设备选择"
          visible={isModalVisible}
          maskClosable={false}
          onOk={() => {
            this.handleOk();
          }}
          onCancel={() => {
            this.handleCancel();
          }}
        >
          <div>
            <Search
              placeholder="请输入要搜索的设备信息"
              value={this.state.searTxt}
              onChange={(e: any) => {
                this.setState({ searTxt: e.target.value });
              }}
              onSearch={(str: string) => {
                this.onSearch(str);
              }}
            />
          </div>
          <Table
            bordered
            columns={this.columns}
            dataSource={this.state.dataSource}
            rowSelection={{
              type: "radio",
              onChange: (selectedRowKeys: React.Key[], selectedRows: any) => {
                this.onSelectChange(selectedRowKeys, selectedRows);
              },
            }}
            pagination={{
              pageSize: this.state.pageSize,
              total: this.state.total,
              current: this.state.pageIndex,
              onChange: (page: number) => {
                this.setState({ pageIndex: page });
                this.getDevices(this.state.searTxt);
              },
            }}
          ></Table>
        </Modal>
      </>
    );
  }
  /**钩子函数 */
  shouldComponentUpdate(
    newProps: SelectDeviceProps,
    newState: SelectDeviceState
  ) {
    if (newState.isModalVisible !== this.state.isModalVisible) {
      if (newState.isModalVisible) {
        this.getDevices();
      }
    }
    return true;
  }
  componentWillMount() {}
  /**操作 */
  //搜索
  onSearch(str: string) {
    this.setState({ pageIndex: 1, pageSize: 5, searTxt: str });
    this.getDevices(str);
  }
  //点击确定
  handleOk = () => {
    this.initValue = this.selectedRow;
    this.setState({ value: this.selectedRow["name"] });
    this.forceUpdate();
    this.props.onSelect(this.selectedRow);
    this.clearSearchState();
  };
  //点击取消
  handleCancel = () => {
    this.clearSearchState();
  };
  //清除查询状态
  clearSearchState() {
    this.setState({
      pageIndex: 1,
      pageSize: 5,
      total: 0,
      searTxt: "",
      isModalVisible: false,
    });
  }
  //打开弹窗
  openTheModal() {
    //打开弹窗
    this.setState({ isModalVisible: true });
  }
  //选择设备
  onSelectChange(selectedRowKeys: React.Key[], selectedRows: any) {
    this.selectedRow = selectedRows[0];
  }
  /**数据请求 */
  async getDtDevicesUrl(pream: any) {
    try {
      let res: any = await getFindDevice(JSON.stringify(pream));
      let json: AjaxData = res;
      if (json.success) {
        this.setState({
          total: json.data.total,
          dataSource: ergodicListAddIdToKey(json.data.records),
        });
        this.forceUpdate();
      }
    } catch (error) {}
  }
  //请求设备列表
  getDevices(likeStr?: string) {
    let { pageIndex, pageSize } = this.state;
    let param = {
      energyType: this.props.energyType,
      likeStr: likeStr ? likeStr : "",
      pageIndex,
      pageSize,
    };
    this.getDtDevicesUrl(param);
  }
}

export default SelectDevice;
